package com.jiao.config;


import com.alibaba.fastjson.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {
    private Logger log = LoggerFactory.getLogger(LogAspect.class);
    ThreadLocal<Long>  startTime = new ThreadLocal<Long>();


    @Pointcut("execution(* com.jiao.controller.*.*(..))")
    public void pointcutName(){}


    @Before("pointcutName()")
    public void methodBefore(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.info("/n");
        //打印请求内容
        log.info("");
        log.info("===============请求内容===============");
        log.info("请求地址:" + request.getRequestURL().toString());
        log.info("请求方式:" + request.getMethod());
        log.info("请求类方法:" + joinPoint.getSignature());
        log.info("请求类方法参数:" + Arrays.toString(joinPoint.getArgs()));
        log.info("===============请求内容===============");
        log.info("");

    }

    @AfterReturning(pointcut = "pointcutName()",returning = "res")
    public void afterExection(Object res){
        log.info("");
        log.info("--------------返回内容----------------");
        log.info("Response内容:" + JSONObject.toJSONString(res));
        log.info("--------------返回内容----------------");
        log.info("请求处理时间为:"+(System.currentTimeMillis() - startTime.get()));
        log.info("");

    }


    @AfterThrowing(throwing="ex",pointcut="pointcutName())")
    public void doRecoveryActions(Throwable ex){
        System.out.println("目标方法中抛出的异常:"+ex);
        System.out.println("模拟抛出异常后的增强处理...");
    }
}